package cn.itcast.Rainbow_self_mention.Activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import cn.itcast.Rainbow_self_mention.R;
import cn.itcast.Rainbow_self_mention.Server.OrderServer;
import cn.itcast.Rainbow_self_mention.Server.PictureReceiver;
import cn.itcast.Rainbow_self_mention.Dao.SqlHelper;

public class Detail_for_rec extends AppCompatActivity {
    TextView NUMBER,
            NAME_OF_SUBMIT,
            PHONE_OF_SUBMIT,
            TIME_OF_ORDER,
            TIME_OF_SUBMIT,
            NAME_OF_RECEIVER,
            PHONE_OF_RECEIVER,
            TIME_OF_RECEIVER,
            LOCATION,
            TEMPERATURE,
            NAME_OF_PRODUCTION;
    qrMyServiceConn conn;
    SqlHelper hp;
    String number;
    int userid;
    ImageView photo, back;
    RelativeLayout take;
    ServiceConn firstconn;
    PictureReceiver.sender sender;
    static String sentresult;
    private Timer timer_for_message;
    static Boolean link = false;
    static OrderServer.Sender qrsender;
    static int i = 0;
    static String c = null;
    static int status = 0;

    class qrMyServiceConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            qrsender = (OrderServer.Sender) service;
            qrsender.get_take_code(userid + "", NUMBER.getText().toString());

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    public void addTimer2() {
        if (timer_for_message == null) {
            timer_for_message = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Looper.prepare();
                    switch (i) {
                        case 1: {
                            Toast.makeText(Detail_for_rec.this, "即将连接图片服务器", Toast.LENGTH_SHORT).show();
                        }
                        case 2: {
                            Toast.makeText(Detail_for_rec.this, "没有上传图片", Toast.LENGTH_SHORT).show();
                        }
                        case 3: {
                            Toast.makeText(Detail_for_rec.this, "图片正在下载", Toast.LENGTH_SHORT).show();
                        }
                        case 4: {
                            Toast.makeText(Detail_for_rec.this, "图片下载完成", Toast.LENGTH_SHORT).show();
                            //onResume();
                            init();
                        }
                    }
                    Looper.loop();
                }
            };
            timer_for_message.schedule(task, 500, 2000);
        }

    }

    class ServiceConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sender = (PictureReceiver.sender) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.untake);
        init();

    }

    @Override
    protected void onResume() {
        super.onResume();
        hp = new SqlHelper(this);
        number = getIntent().getStringExtra("number");


        Intent server = new Intent(this, PictureReceiver.class); //创建意图对象
        firstconn = new ServiceConn();//创建服务连接对象
        getApplicationContext().bindService(server, firstconn, BIND_AUTO_CREATE);


        Intent s = new Intent(this, OrderServer.class);
        conn = new qrMyServiceConn();
        getApplicationContext().bindService(s, conn, BIND_AUTO_CREATE);


        try {
            initdate();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        initbutton();

        SQLiteDatabase db = hp.getReadableDatabase();
        Cursor cursor = db.query("logined", new String[]{"userid"}, "_id=?", new String[]{"1"}, null, null, null);
        cursor.moveToFirst();

        userid = cursor.getInt(cursor.getColumnIndex("userid"));
        db.close();
        cursor.close();
        Log.i("qrsender", qrsender + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (isFinishing()) {
            if (firstconn != null) {
                getApplicationContext().unbindService(firstconn);
            }
            if (conn != null) {
                getApplicationContext().unbindService(conn);
            }
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void initbutton() {
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SQLiteDatabase db = hp.getReadableDatabase();
                Cursor cursor = db.query("HISTORY", new String[]{"NAME_OF_PICTURE","NUMBER"}, "NUMBER=?", new String[]{number}, null, null, null);
                cursor.moveToFirst();
                String name = cursor.getString(cursor.getColumnIndex("NAME_OF_PICTURE"));
                String orderid = cursor.getString(cursor.getColumnIndex("NUMBER"));
                cursor.close();
                cursor = db.query("logined", null, null, null, null, null, null);
                cursor.moveToFirst();
                int userid = cursor.getInt(cursor.getColumnIndex("userid"));
                db.close();
                cursor.close();
                sender.sm("7", name, userid, orderid);
                addTimer2();
            }
        });
        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (status != 1) {
                    Toast.makeText(Detail_for_rec.this, "获取取件码失败", Toast.LENGTH_LONG).show();
                } else {
                    SQLiteDatabase db = hp.getReadableDatabase();
                    Cursor cursor = db.query("logined", new String[]{"username"}, "_id=?", new String[]{"1"}, null, null, null);
                    cursor.moveToFirst();
                    Intent intent = new Intent();
                    intent.setClass(Detail_for_rec.this, QRCodeActivity.class);
                    intent.putExtra("username", cursor.getString(cursor.getColumnIndex("username")) + "");
                    intent.putExtra("stance", "取件码");
                    intent.putExtra("code", c);
                    cursor.close();
                    db.close();
                    startActivity(intent);
                    overridePendingTransition(0, 0);

                }
            }
        });
    }

    public void init() {
        NUMBER = findViewById(R.id.history_number);
        NAME_OF_SUBMIT = findViewById(R.id.history_putpeople);
        PHONE_OF_SUBMIT = findViewById(R.id.history_putpeolputnumber);
        TIME_OF_ORDER = findViewById(R.id.history_ordertime);
        TIME_OF_SUBMIT = findViewById(R.id.history_puttime);
        NAME_OF_RECEIVER = findViewById(R.id.history_takepeople);
        PHONE_OF_RECEIVER = findViewById(R.id.history_takenumber);
        TIME_OF_RECEIVER = findViewById(R.id.history_taketime);
        LOCATION = findViewById(R.id.history_address);
        NAME_OF_PRODUCTION = findViewById(R.id.history_name_of_good);
        photo = findViewById(R.id.image);
        take = findViewById(R.id.take);
        TEMPERATURE = findViewById(R.id.TEMPERATURE);
        back = findViewById(R.id.history_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Detail_for_rec.this, Home.class);
                startActivity(intent);
                finish();
            }
        });


    }

    public void initdate() throws FileNotFoundException {
        SQLiteDatabase db = hp.getReadableDatabase();
        Cursor cursor = db.query("HISTORY", null, "NUMBER=?", new String[]{number}, null, null, null);
        cursor.moveToFirst();
        NUMBER.setText(cursor.getString(cursor.getColumnIndex("NUMBER")));
        NAME_OF_SUBMIT.setText(cursor.getString(cursor.getColumnIndex("NAME_OF_SUBMIT")));
        PHONE_OF_SUBMIT.setText(cursor.getString(cursor.getColumnIndex("PHONE_OF_SUBMIT")));
        TIME_OF_ORDER.setText(cursor.getString(cursor.getColumnIndex("TIME_OF_ORDER")));
        TIME_OF_SUBMIT.setText(cursor.getString(cursor.getColumnIndex("TIME_OF_SUBMIT")));
        NAME_OF_RECEIVER.setText(cursor.getString(cursor.getColumnIndex("NAME_OF_RECEIVER")));
        PHONE_OF_RECEIVER.setText(cursor.getString(cursor.getColumnIndex("PHONE_OF_RECEIVER")));
        TIME_OF_RECEIVER.setText(cursor.getString(cursor.getColumnIndex("TIME_OF_RECEIVER")));
        LOCATION.setText(cursor.getString(cursor.getColumnIndex("LOCATION")));
        TEMPERATURE.setText(cursor.getString(cursor.getColumnIndex("TEMPERATURE")) + "℃");
        NAME_OF_PRODUCTION.setText(cursor.getString(cursor.getColumnIndex("NAME_OF_PRODUCTION")));
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "MTZTG";
        File appDir = new File(root, dirName);
        String fileName = cursor.getString(cursor.getColumnIndex("NAME_OF_PICTURE"));
        File file = new File(appDir, fileName);
        if(file.exists()){
        Uri imageuri = FileProvider.getUriForFile(this, "Rainbow_self_mention", file);
        InputStream input = getContentResolver().openInputStream(imageuri);
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        photo.setImageBitmap(bitmap);}
        cursor.close();
        db.close();
    }

    public static Handler handler = new Handler() {//创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            sentresult = bundle.getString("sentresult");

            //Log.i("sentresult=",sentresult);
            if (sentresult.equals("404")) {
                i = 0;
            }
            if (sentresult.equals("1")) {
                i = 1;
            }
            if (sentresult.equals("2")) {
                i = 2;
            }
            if (sentresult.equals("3")) {
                i = 3;
            }
            if (sentresult.equals("4")) {
                i = 4;
            }
            if (sentresult.equals("34")) {
                link = true;
            }
            if (sentresult.equals("35")) {
                link = false;
            }
            if (sentresult.equals("91")) {
                status = 1;
                c = bundle.getString("code");
            }
            if (sentresult.equals("93")) {
                status = 3;
            }
            if (sentresult.equals("94")) {
                status = 4;
            }
            if (sentresult.equals("95")) {
                status = 5;
            }
        }
    };
}
